package com.androidxmpp.fragment;

import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.androidxmpp.AboutActivity;
import com.androidxmpp.FeedBackActivity;
import com.androidxmpp.LoginActivity;
import com.androidxmpp.MainActivity;
import com.androidxmpp.R;
import com.androidxmpp.config.PreferenceConstants;
import com.androidxmpp.service.XMPPService;
import com.androidxmpp.util.DialogUtil;
import com.androidxmpp.util.PreferenceUtils;
import com.androidxmpp.util.XMPPHelper;

/**
 * 右边设置
 * 
 * @author chen_fulei
 * 
 */
public class SettingsFragment extends Fragment implements OnClickListener {

	private View view;
	private FragmentCallBack mFragmentCallBack;

	private TextView ivTitleName;
	private RelativeLayout set_user;
	private RelativeLayout set_add;
	private RelativeLayout set_feedback;
	private RelativeLayout set_about;

	private Button exit_app;
	private ImageView iv_face;
	private ImageView iv_statusIcon;
	private TextView txt_username;
	private TextView txt_status;

	private View mExitView;
	private Button btn_exit_comfirm;
	private Button btn_cancel;

	private Dialog mExitDialog;
	private ArrayAdapter<String> mGroupAdapter ;
	private String mAddGroupString;
	private String mDefaultGroup;
	EditText edit_username ;
	EditText edit_nickname;
	EditText edit_newgroupinput;

	public static SettingsFragment getInstance() {
		return new SettingsFragment();
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);

		try {
			mFragmentCallBack = (FragmentCallBack) activity;
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		mExitView = LayoutInflater.from(getActivity()).inflate(
				R.layout.common_menu_dialog_2btn_layout, null);
		btn_exit_comfirm = (Button) mExitView
				.findViewById(R.id.btn_exit_comfirm);
		btn_exit_comfirm.setText("退出");
		btn_cancel = (Button) mExitView.findViewById(R.id.btnCancel);
		btn_exit_comfirm.setOnClickListener(this);
		btn_cancel.setOnClickListener(this);

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.frame_setting, null);
		ivTitleName = (TextView) view.findViewById(R.id.ivTitleName);
		ivTitleName.setVisibility(View.VISIBLE);
		ivTitleName.setText("设置");

		set_user = (RelativeLayout) view.findViewById(R.id.set_user);
		set_add = (RelativeLayout) view.findViewById(R.id.set_add);
		set_feedback = (RelativeLayout) view.findViewById(R.id.set_feedback);
		set_about = (RelativeLayout) view.findViewById(R.id.set_about);

		exit_app = (Button) view.findViewById(R.id.exit_app);
		iv_face = (ImageView) view.findViewById(R.id.iv_face);
		iv_statusIcon = (ImageView) view.findViewById(R.id.iv_statusIcon);
		txt_username = (TextView) view.findViewById(R.id.txt_username);
		txt_status = (TextView) view.findViewById(R.id.txt_status);

		set_user.setOnClickListener(this);
		set_add.setOnClickListener(this);
		set_feedback.setOnClickListener(this);
		set_about.setOnClickListener(this);
		exit_app.setOnClickListener(this);
		return view;
	}

	@Override
	public void onResume() {
		super.onResume();
		readData();
	}

	public void readData() {
		iv_face.setImageResource(R.drawable.ic_launcher);
		iv_statusIcon.setImageResource(MainActivity.mStatusMap
				.get(PreferenceUtils.getPrefString(getActivity(),
						PreferenceConstants.STATUS_MODE,
						PreferenceConstants.AVAILABLE)));
		txt_status.setText(PreferenceUtils.getPrefString(getActivity(),
				PreferenceConstants.STATUS_MESSAGE,
				getActivity().getString(R.string.status_available)));

		txt_username
				.setText(XMPPHelper.splitJidAndServer(PreferenceUtils
						.getPrefString(getActivity(),
								PreferenceConstants.ACCOUNT, "")));
	}

	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.set_user:
			logoutDialog();
			break;
		case R.id.set_feedback:
			startActivity(new Intent(getActivity(), FeedBackActivity.class));
			getActivity().overridePendingTransition(R.anim.enteralpha, R.anim.exitalpha);
			break;

		case R.id.set_add:
			XMPPService xxService = mFragmentCallBack.getService();
			if (xxService == null || !xxService.isAuthenticated()) {
				return;
			}
			addDialog(xxService);
			break;

		case R.id.set_about:
			startActivity(new Intent(getActivity(), AboutActivity.class));
			getActivity().overridePendingTransition(R.anim.enteralpha, R.anim.exitalpha);
			break;

		case R.id.exit_app:
			if (mExitDialog == null)
				mExitDialog = DialogUtil
						.getMenuDialog(getActivity(), mExitView);
			mExitDialog.show();
			break;

		case R.id.btn_exit_comfirm:
			XMPPService service = mFragmentCallBack.getService();
			if (service != null) {
				service.logout();
				service.stopSelf();
			}

			if (mExitDialog.isShowing()) {
				mExitDialog.cancel();
			}
			getActivity().finish();
			break;

		case R.id.btnCancel:
			if (mExitDialog != null && mExitDialog.isShowing())
				mExitDialog.dismiss();
			break;
		default:
			break;
		}
	}

	public void addDialog(final XMPPService service){
		mAddGroupString = getActivity().getString(R.string.addrosteritemaddgroupchoice);
		mDefaultGroup = getActivity().getString(R.string.default_group);
		View vp = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_add, null);
		final Dialog dialog =DialogUtil.getAlertDialogWarp(getActivity(), vp);
		
		edit_username = (EditText) vp.findViewById(R.id.edit_username);
		edit_nickname = (EditText) vp.findViewById(R.id.edit_nickname);
		edit_newgroupinput = (EditText) vp.findViewById(R.id.edit_newgroupinput);
		final Button btn_ok = (Button) vp.findViewById(R.id.btn_ok);
		btn_ok.setEnabled(false);
		Button btn_cancel = (Button) vp.findViewById(R.id.btn_cancel);
		final Spinner spinner = (Spinner) vp.findViewById(R.id.spinner);
		
		List<String> getRosterGroups = mFragmentCallBack.getMainActivity().getRosterGroups();
		getRosterGroups.remove("");
		getRosterGroups.add(0, mDefaultGroup);
		getRosterGroups.add(mAddGroupString);
		mGroupAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, getRosterGroups);
		mGroupAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner.setAdapter(mGroupAdapter);
		spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View convertView,
					int position, long index) {
				if(parent.getSelectedItem().toString().equals(mAddGroupString)){
					edit_newgroupinput.setVisibility(View.VISIBLE);
				}else{
					edit_newgroupinput.setVisibility(View.GONE);
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				
			}
		});
		
		btn_ok.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				
				String spinnerItem = spinner.getSelectedItem().toString();
				if(spinnerItem.equals(mAddGroupString)){
					spinnerItem = edit_newgroupinput.getText().toString();
				}
				service.addRosterItem(edit_username.getText()
						.toString(), edit_nickname.getText().toString(),spinnerItem);
				
				dialog.dismiss();
			}
		});
		
		btn_cancel.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				dialog.dismiss();
			}
		});
		
		edit_username.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				try {
					XMPPHelper.verifyJabberID(s);
					btn_ok.setEnabled(true);
					edit_username.setTextColor(XMPPHelper.getEditTextColor(getActivity()));
				} catch (Exception e) {
					btn_ok.setEnabled(false);
					edit_username.setTextColor(Color.RED);
				}
			}
		});
		
	}
	
	public void logoutDialog() {
		new AlertDialog.Builder(getActivity())
				.setTitle(getActivity().getString(R.string.open_switch_account))
				.setMessage(
						getActivity().getString(
								R.string.open_switch_account_msg))
				.setPositiveButton(android.R.string.yes,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								XMPPService service = mFragmentCallBack
										.getService();
								if (service != null) {
									service.logout();// 注销
								}
								dialog.dismiss();
								startActivity(new Intent(getActivity(),
										LoginActivity.class));
								getActivity().finish();
							}
						})
				.setNegativeButton(android.R.string.no,
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								dialog.dismiss();
							}
						}).create().show();
	}

}
